<template>
  <div>
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item label="持续时间：" props="duration"
        :rules="[
          { required: true, message: '请选择类型'}
        ]">
        <el-input-number
          v-model="form.duration"
          controls-position="right"
          :controls="true" 
          @change="handleChange" :min="1" :max="10" />
          <span style="margin-left: 5px;">分钟</span>
      </el-form-item>
      <div class="center" style="margin-bottom: 30px;">
          <img :src="currentFrame.src">
          <div style="margin-top:20px;">
            <el-button class="arrow-btn" type="text" :disabled="currentFrameIndex<=0" @click="preFrame">&lt;</el-button>
            <div class="cur-frame">
              第<el-input-number class="center board-frame-input" :min="1" :max="frameLength"
                  v-model="currentIndex"  />帧
            </div>
            <el-button class="arrow-btn" type="text" :disabled="currentFrameIndex>=(playbook && playbook.frames ? playbook.frames.length -1: 0 )" @click="nextFrame">&gt;</el-button>
          </div>
      </div>
      <div>
        <h2>参数设置</h2>
        <el-row>
          <el-col :span="8">
            <el-form-item label="参与人数：" props="playerNumber">
              <el-select class="borad-select" v-model="form.playerNumber">
                <el-option
                  v-for="item in 12"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label="球数：" props="">
              <el-select class="borad-select" v-model="form.ballNumber">
                <el-option
                  v-for="item in 12"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label="篮筐数：" props="">
              <el-select class="borad-select" v-model="form.basketNumber">
                <el-option
                  v-for="item in 2"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="器械数量：" props="">
              <el-select class="borad-select" v-model="form.equipmentNumber">
                <el-option
                  v-for="item in 20"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label="分组：" props="">
              <el-select class="borad-select" v-model="form.isGroup">
                <el-option
                  v-for="item in IsGroup"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-form-item label="其他：" props="" label-width="68px">
              <el-input class="borad-select" :maxlength="20" v-model.trim="form.other"/>
            </el-form-item>
          </el-col>
        </el-row>
        <e-editor
          v-model.trim="form.describe"
          :maxlength="2000" >
        </e-editor>
      </div>
    </el-form>
    <div ref="describe" id="describe" style="display:none">
    </div>

    <div class="center" style="margin-top: 60px;">
      <el-button>取消</el-button>
      <el-button type="primary" @click="submit">保存 </el-button>
    </div>
  </div>
</template>
<script>
import ESliderbox from '@e-ui/Sliderbox'
import EEditor from '@e-ui/Editor'
import api from 'api/tactics'
import {BasketBallPlaybook} from 'utils/playbook'

export default{
  props: {
    sportType: [String, Number],
    tacticTypeId: [String, Number],
    tacticId: [String, Number],
    currentTab: String
  },
  components: {
    ESliderbox,
    EEditor
  },
  computed: {
    tacticsType () {
      return this.$store.getters.tactics_type_list
    },
    tacticsList () {
      return this.$store.getters.tactics_list
    },
    tacticsInfo () {
      return this.$store.getters.tactics_info || {}
    },
    frameLength () {
      if (this.playbook && this.playbook.frames) {
        return this.playbook.frames.length
      } else {
        return 1
      }
    },
    currentIndex: {
      get () {
        return this.currentFrameIndex + 1
      },
      set (val) {
        if (val < 0) {
          this.currentFrameIndex = 0
        } else if (val > this.frameLength) {
          this.currentFrameIndex = this.frameLength - 1
        } else {
          this.currentFrameIndex = val - 1
        }
      }
    }
  },
  mounted () {
    this.$nextTick(function () {
      let dom = this.$refs['describe']
      this.playbook = new BasketBallPlaybook(dom)
      window.that = this
    })
  },
  watch: {
    'tacticsInfo.id' (id) {
      if (id) {
        let info = this.tacticsInfo
        this.playbook.clear()
        // this.playbook.update()
        this.currentFrameIndex = 0
        let hasFrame = info.frames || info.sprites
        let type = info.type
        this.drawBg(type, hasFrame)
        this.resetForm()
      }
    },
    currentIndex (newVal, oldVal) {
      if (newVal !== oldVal) {
        this.handleBlur(newVal, oldVal)
      }
    },
    currentTab (val, oldVal) {
      // debugger
      if (val !== oldVal && val === 'description') {
        let type = this.tacticsInfo.type || this.playbook.type
        let hasFrame = this.tacticsInfo.frames || this.tacticsInfo.sprites
        if (hasFrame) {
          this.playbook.deserialize(this.tacticsInfo)
          this.playbook.update()
          this.currentFrame.src = this.playbook.toDataURL(this.playbook.frames[this.currentFrameIndex], this.quality)
          this.resetForm(this.currentFrameIndex)
        } else {
          this.drawBg(type, hasFrame)
        }
      }
    }
  },
  data () {
    let playbook
    return {
      quality: 0.5,
      playbook,
      frameList: [],
      rules: {},
      form: {
        duration: 1, // 持续时间
        playerNumber: '', // 参与人数
        ballNumber: '',
        basketNumber: '', // 篮筐数
        equipmentNumber: '', // 器械
        isGroup: 0, // 是否分组，
        other: '',
        describe: '' // 描述
      },
      IsGroup: [
        {
          label: '分组',
          value: 1
        },
        {
          label: '不分组',
          value: 0
        }
      ],
      currentFrame: {
        src: ''
      },
      currentFrameIndex: 0
    }
  },
  methods: {
    handleChange () {
    },
    preFrame () {
      if (this.currentFrameIndex <= 0) {
        return false
      }
      this.currentFrameIndex--
      this.playbook.index--
      // console.log(this.currentFrameIndex)
    },
    nextFrame () {
      if (this.currentFrameIndex >= this.playbook.frames.length - 1) {
        return false
      }
      this.currentFrameIndex++
      this.playbook.index++
      // console.log(this.currentFrameIndex)
    },
    submit () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.setOptions()
          let content = this.playbook.serialize()
          let postdata = {
            sportTypeId: this.sportType,
            tacticTypeId: this.tacticTypeId,
            id: this.tacticId,
            content: content
          }
          api.update(postdata).then((res) => {
            let data = JSON.parse(this.playbook.serialize())
            this.$store.commit('TACTICS_INFO', Object.assign({}, data, {
              id: this.tacticId,
              key: Math.random().toString(36).substr(2)
            }))
          })
        } else {
          return false
        }
      })
    },
    drawBg (type, hasFrame) {
      if (type === 2 || type === 'half-up') {
        this.playbook.type = 'half-up'
      } else if (type === 3 || type === 'half-down') {
        this.playbook.type = 'half-down'
      } else {
        this.playbook.type = 'full'
      }
      this.playbook.designMode = true
      this.playbook.deserialize(this.tacticsInfo)
      let cFrame = this.playbook.currentFrame
      this.playbook.update()
      if (!hasFrame) { // 如果没有帧,则插入一个默认帧
        this.insertImage(cFrame)
      } else {
        this.currentFrame.src = this.playbook.toDataURL(cFrame, this.quality)
      }
    },
    insertImage (frame) {
      var img = new Image()
      frame.image = img
      img.frame = frame
      img.src = this.playbook.toDataURL(frame, this.quality)
      this.currentFrame.src = img.src
    },
    resetForm (index) {
      // debugger
      let cframe = this.playbook.frames[index] || this.playbook.frames[this.currentFrameIndex]
      const attrs = ['duration', 'playerNumber', 'ballNumber', 'basketNumber', 'equipmentNumber', 'other']
      attrs.forEach(item => {
        this.form[item] = cframe[item]
      })
      this.form.describe = decodeURIComponent(cframe.describe)
      this.form.isGroup = cframe.isGroup ? 1 : 0
    },
    // 保存当前帧的数据
    setOptions (index) {
      let frame = this.playbook.frames[index] || this.playbook.frames[this.currentFrameIndex]
      let form = this.form
      if (form.duration > 1 || frame.duration !== form.duration) {
        frame.duration = form.duration
      }
      if (form.playerNumber > 0 || frame.playerNumber !== form.playerNumber) {
        frame.playerNumber = form.playerNumber
      }
      if (form.ballNumber > 0 || frame.ballNumber !== form.ballNumber) {
        frame.ballNumber = form.ballNumber
      }
      if (form.basketNumber > 0 || frame.basketNumber !== form.basketNumber) {
        frame.basketNumber = form.basketNumber
      }
      if (form.equipmentNumber > 0 || frame.equipmentNumber !== form.equipmentNumber) {
        frame.equipmentNumber = form.equipmentNumber
      }
      if (frame.isGroup !== form.isGroup) {
        frame.isGroup = form.isGroup
      }
      if (form.other || frame.other !== form.other) {
        frame.other = form.other
      }
      if (form.describe || frame.describe !== form.describe) {
        // frame.describe = encodeURIComponent(form.describe)
        frame.describe = form.describe
      }
    },
    handleBlur (newVal, old) {
      let frame = (this.playbook && this.playbook.frames && this.playbook.frames.length) ? this.playbook.frames[newVal - 1] : 0
      this.currentFrame.src = this.playbook.toDataURL(frame, this.quality)
      this.setOptions(old - 1)
      this.resetForm(newVal - 1)
    }
  }
}
</script>
<style lang="scss">
.borad-select{
  width: 170px!important;
}
.board-frame-input{
  display:inline-block;
  width:50px;
  margin:0 5px;
  .el-input__inner{
    text-align: center;
  }
}
</style>